<?php
/**
 * Created by PhpStorm.
 * User: allen
 * Date: 2019/3/8
 * Time: 10:38
 */
namespace app\index\controller;

use app\index\model\LotteryLog;
use app\index\model\Member;
use think\App;
use Naixiaoxin\ThinkWechat\Facade;


class Pay extends Base {

//    protected $middleware = ['Wechat'];
    protected static $payment  = null;

    public function __construct(App $app = null){
        parent::__construct($app);
        self::$payment = Facade::payment();
    }
    /**
     * 创建订单
     * @param string $title
     * @param int $fee
     * @param string $open_id
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function create_order($title='',$fee=0){
        if(!$title){
            return json(['code'=>1,'msg'=>'请填写订单主题']);
        }
        if(!$fee){
            return json(['code'=>1,'msg'=>'请填写订单金额']);
        }
        $member = new Member();
        $info = $member->get(self::$uid);
        $open_id = $info['open_id'];
        $_data = $order = [
            'body' => $title,
            'out_trade_no' => build_order_no(),
            'total_fee' => $fee * 100,
            'trade_type' => 'JSAPI',
            'openid' => $open_id
        ];
        $_data['create_time']=time();
        $_data['title']=$title;
        $_data['openid']= $open_id;
        $_data['total_fee'] = $fee;
        $_data['uid'] = self::$uid;
        if(!db('orderlist')->insert($_data)){
            return json(['code'=>1,'msg'=>'订单创建失败,请稍后再试']);
        }
        $result = self::$payment->order->unify($order);
        $_config = self::$payment->jssdk
            ->bridgeConfig($result['prepay_id'], true);
        return json(['code'=>0,'msg'=>'成功','out_trade_no'=> $_data['out_trade_no'],'js_api'=>$_config]);
    }

    /**
     * @param string $out_trade_no
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function query_order($out_trade_no=''){
        if(!$out_trade_no){
            return json(['code'=>1,'msg'=>'请填写查询单号']);
        }
        $order = db('orderlist')
            ->where('out_trade_no','eq',$out_trade_no)
            ->find();
        if(!$order){
            return json(['code'=>1,'msg'=>'查询订单不存在']);
        }
        $result = self::$payment->order
            ->queryByOutTradeNumber($out_trade_no);
        if($result['trade_state']=='SUCCESS' && $result['result_code']=='SUCCESS'){
            db('orderlist')->where('id','eq',$order['id'])
                ->update([
                    'id'=> $order['id'],
                    'payment_trade_no'=>$result['transaction_id'],
                    'finish_time'=>time(),
                    'payment_notify_time'=>$result['time_end'],
                    'payment_trade_status'=>$result['trade_state_desc'],
                    'status'=>2
                ]);
            return json(['code'=>0,'msg'=>'查询订单支付成功']);
        }else{
            db('orderlist')
                ->update([
                    'id'=>$order['id'],
                    'finish_time'=>time(),
                    'status'=>3
                ]);
            return json(['code'=>1,'msg'=>'查询订单支付失败']);
        }
    }

    /**
     * 发送红包
     * @param int $lid
     * @param int $mid
     * @param string $title
     * @param string $remark
     * @param int $type
     * @param array $data
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function redpack($lid=0,$title='分享红包',
        $remark='分享活动领现金红包',$type=1,$data=[]){
        if(!$lid){
            return $this->__json(1,'缺少参数');
        }
        $log = new LotteryLog();
        if($type==1){
            $lottery = $log->getMoney($lid,self::$uid,$title,$remark,$out);
            if(!$lottery){
                return $this->__json(1,$out);
            }
            $redpackData = $out;
            $log->where('id','eq',$lid)
                ->update(['order_id'=>$out['mch_billno']]);
        }elseif($type==2){
            $redpackData = $data;
        }
        $result = self::$payment->redpack->sendNormal($redpackData);
        if($result['err_code']=='SENDNUM_LIMIT'){
            if($log->updateStatus($lid,4,$result['return_msg'])){
                return $this->__json(3,'今日领取次数超限');
            }
        }
        if($result['err_code']=='SYSTEMERROR'){
            if($log->updateStatus($lid,4,$result['return_msg'])){
                return $this->__json(1,'领取失败',['data'=>$redpackData]);
            }
        }
        if($result['err_code']=='NO_AUTH'){
            if($log->updateStatus($lid,4,$result['return_msg'])){
                return $this->__json(3,$result['return_msg']);
            }
        }
        if($result['err_code']=='SEND_FAILED'){
            if($log->updateStatus($lid,3,$result['return_msg'])){
                return $this->__json(3,'领取失败');
            }
        }
        if($result['result_code']=='SUCCESS'){
            $res = $log->decMoney($lid,$result['return_msg'],$out);
            if(!$res){
               return $this->__json(3, $out);
            }
            return $this->__json(0,'领取成功',['order_id'=>$out['mch_billno']]);
        }else{
            return $this->__json(3,'领取失败');
        }
    }

    /**
     * 查询红包结果
     * @param string $order_id
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function redpack_query($order_id=''){
        if(!$order_id){
            return $this->__json(1,'缺少参数');
        }
        $result = self::$payment->redpack->info($order_id);

        if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
            if($result['status']=='SENT' || $result['status']=='RECEIVED'){
                $log = new LotteryLog();
                $res = $log->decMoneyByOrderId($order_id,$result['status'],$result['return_msg'],$result['hblist'],$out);
                if(!$res){
                    return $this->__json(1,$result['err_code'].':'.$result['err_code_des']);
                }
                return $this->__json(0,'领取成功');
            }
        }else{
            return $this->__json(1,$result['err_code'].':'.$result['err_code_des']);
        }
    }

    /**
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function query_all_redpack(){
        ignore_user_abort(true);
        set_time_limit(0);
        $now   = new \DateTime;
        $clone = clone $now;
        $clone->modify( '-30 min' );
        $start = $clone->format( 'Y-m-d H:i:s');
        $end = $now->format( 'Y-m-d H:i:s');

        $log = new LotteryLog();
        $list = $log
            ->whereBetweenTime('create_time',$start,$end)
//            ->where('status','neq',2)
            ->select();
        $log = new LotteryLog();
        $redpack = [];
        foreach ($list as $k => $v){
            $order_id = $v['order_id'];
            if(!$order_id) continue;
            $lid = $v['lid'];
            $result = self::$payment->redpack->info($order_id);
            /*
             SENDING:发放中
             SENT:已发放待领取
             FAILED：发放失败
             RECEIVED:已领取
             RFUND_ING:退款中
             REFUND:已退款
             */
            if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
                $data = [
                    'id'=>$v['id'],
                    'order_id'=>$order_id,
                    'return_code'=>$result['return_code'],
                    'set_info'=>$result['return_msg'],
                    'hblist'=>(isset($result['hblist']) && $result['hblist'])
                        ?json_encode($result['hblist']):'',
                ];
                if($result['status']=='SENT' || $result['status']=='RECEIVED'){
//                    $res = $log->decMoneyByOrderId($order_id,$result['status'],$result['return_msg'],$result['hblist'],$out);
                    $data['status']=2;
                }elseif($result['status']=='FAILED'){
                    $data['status']=3;
//                    $log->updateStatus($lid,4,$result['return_msg']);
                }elseif($result['status']=='SENDING'){
                    $data['status']=4;
//                    $log->updateStatus($lid,1,$result['return_msg']);
                }else{
                    $data['status']=4;
//                    $log->updateStatus($lid,2,$result['return_msg']);
                }
            }
            array_push($redpack,$data);
        }
        $log->saveAll($redpack);
        $str = '本次共查询了'.count($redpack).'条记录。';
        file_put_contents("./{$start}_{$end}|红包查询.txt",$str.json_encode($redpack));
        echo $str;
    }
}